// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    motto: 'Hello',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    description: '加载中...',
    // 活动列表相关数据
    activityList: [],
    pageNumber: 1,
    hasMoreActivities: true,
    isLoadingActivities: false
  },

  onLoad() {
    this.getDescription()
    this.getActivityList()
  },

  getDescription() {
    wx.request({
      url: 'https://jingliange.com/api/v1/about/getDescription',
      method: 'GET',
      success: (res) => {
        // console.log('获取文字介绍成功:', res)
        if (res.statusCode === 200 && res.data) {
          this.setData({
            description: res.data.data.data || res.data.data || '暂无介绍'
          })
        } else {
          this.setData({
            description: '暂无介绍'
          })
        }
      },
      fail: (err) => {
        console.error('获取文字介绍失败:', err)
        this.setData({
          description: '加载失败，请稍后重试'
        })
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        })
      },
      complete: () => {
        wx.stopPullDownRefresh()
      }
    })
  },

  onPullDownRefresh() {
    this.getDescription()
    this.getActivityList(true) // 刷新活动列表
  },

  onReachBottom() {
    if (this.data.hasMoreActivities && !this.data.isLoadingActivities) {
      this.getActivityList()
    }
  },

  formatTime(timeStr) {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  },

  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },

  // 获取活动列表
  getActivityList(isRefresh = false) {
    if (this.data.isLoadingActivities) return
    
    const pageNumber = isRefresh ? 1 : this.data.pageNumber
    
    this.setData({
      isLoadingActivities: true
    })

    const params = {
      timestamp: Date.now(),
      pageNumber: pageNumber
    }

    wx.request({
      url: 'https://jingliange.com/api/v1/about/getActivityList',
      method: 'POST',
      data: params,
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        // console.log('获取活动列表成功:', res.data)
        if (res.statusCode === 200 && res.data.code === 200) {
          const newActivities = (res.data.data || []).map(item => ({
            ...item,
            formattedTime: this.formatTime(item.create_time)
          }))
          
          if (isRefresh) {
            // 刷新时替换数据
            this.setData({
              activityList: newActivities,
              pageNumber: 1,
              hasMoreActivities: newActivities.length > 0
            })
          } else {
            // 加载更多时追加数据
            this.setData({
              activityList: [...this.data.activityList, ...newActivities],
              pageNumber: pageNumber + 1,
              hasMoreActivities: newActivities.length > 0
            })
          }
        } else {
          wx.showToast({
            title: res.data.msg || '获取活动列表失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: (err) => {
        console.error('获取活动列表失败:', err)
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        })
      },
      complete: () => {
        this.setData({
          isLoadingActivities: false
        })
        wx.stopPullDownRefresh()
      }
    })
  },
})
